<script lang="ts">
  import {
    list as list_member,
    type MemberInfo,
    remove as remove_member,
    set_admin,
  } from "$lib/api/board/board_member";
  import AsyncImage from "$lib/components/image/AsyncImage.svelte";
  import { boardStore } from "$lib/stores/board.svelte";
  import { userStore } from "$lib/stores/user.svelte";
  import { request } from "$lib/utils/request";
  import RemoveModal from "$lib/components/modal/RemoveModal.svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  import { getContext } from "svelte";
  import EditSelect from "$lib/components/editable/EditSelect.svelte";
  import InviteModal from "./InviteModal.svelte";

  const toast: ToastStore = getContext("toast");

  let showInviteModal = $state(false);

  let memberList = $state([] as MemberInfo[]);

  let hoverMemberUserId = $state("");

  let removeMemberInfo = $state(null as null | MemberInfo);

  async function loadMemberList() {
    const res = await request(
      list_member({
        session_id: userStore.userSession,
        board_id: boardStore.curBoardId,
      }),
    );
    memberList = res.member_list;
  }

  async function updateAdmin(
    memberUserId: string,
    admin: boolean,
  ): Promise<boolean> {
    await request(
      set_admin({
        session_id: userStore.userSession,
        board_id: boardStore.curBoardId,
        member_user_id: memberUserId,
        admin: admin,
      }),
    );
    const tmpList = memberList.slice();
    const index = tmpList.findIndex(
      (item) => item.member_user_id == memberUserId,
    );
    if (index != -1) {
      tmpList[index].admin = admin;
      memberList = tmpList;
    }

    return true;
  }

  async function removeMember() {
    if (removeMemberInfo == null) {
      return;
    }
    await request(
      remove_member({
        session_id: userStore.userSession,
        board_id: boardStore.curBoardId,
        member_user_id: removeMemberInfo.member_user_id,
      }),
    );
    toast.create({
      title: "成功",
      description: "移除成员成功!",
      type: "success",
    });
    await loadMemberList();
    removeMemberInfo = null;
  }

  $effect(() => {
    if (userStore.userSession != "") {
      loadMemberList();
    }
  });
</script>

<div
  class="card border-[1px] border-surface-200-800 w-full p-0 rounded-[10px] bg-surface-100-900"
>
  <header
    class="border-b-[2px] border-surface-200-800 flex justify-between bg-surface-200-800 pl-2 pr-2 rounded-t-[10px]"
  >
    <h4 class="h4">成员列表</h4>
    {#if boardStore.curWebBoard?.myMember?.admin == true}
      <div>
        <button
          type="button"
          class="btn preset-filled-primary-900-100 rounded-[10px] h-[30px] mt-[4px]"
          onclick={() => (showInviteModal = true)}>邀请成员</button
        >
      </div>
    {/if}
  </header>

  <div class="table-wrap">
    <table class="table">
      <thead>
        <tr>
          <th>成员名称</th>
          <th>权限</th>
          <th class="w-[150px]">操作</th>
        </tr>
      </thead>
      <tbody>
        {#each memberList as boardMember}
          <tr
            class="hover:preset-tonal h-[50px]"
            onmouseenter={() =>
              setTimeout(() => {
                hoverMemberUserId = boardMember.member_user_id;
              }, 100)}
            onmouseleave={() => (hoverMemberUserId = "")}
          >
            <td>
              <div class="flex gap-2">
                <AsyncImage
                  src={boardMember.member_logo_uri}
                  sizeClass="w-[20px] h-[20px]"
                  borderClass="rounded-[10px]"
                />
                {boardMember.member_display_name}
              </div>
            </td>
            <td>
              <div class="flex flex-wrap gap-2">
                <EditSelect
                  value={boardMember.admin ? "1" : "0"}
                  canEdit={boardMember.user_perm.can_update_perm}
                  widthClass="w-full"
                  optionList={[
                    {
                      label: "管理员",
                      value: "1",
                    },
                    {
                      label: "普通成员",
                      value: "0",
                    },
                  ]}
                  onChange={(newValue) =>
                    updateAdmin(boardMember.member_user_id, newValue == "1")}
                />
              </div>
            </td>
            <td>
              {#if hoverMemberUserId == boardMember.member_user_id && boardMember.user_perm.can_remove}
                <button
                  type="button"
                  class="btn preset-filled-error-200-800"
                  onclick={() => {
                    removeMemberInfo = boardMember;
                  }}>删除</button
                >
              {/if}
            </td>
          </tr>
        {/each}
      </tbody>
    </table>
  </div>
</div>

<div class="absolute -left-[10000px]">
  {#if showInviteModal}
    <InviteModal onClose={() => (showInviteModal = false)} />
  {/if}
  {#if removeMemberInfo != null}
    <RemoveModal
      title="移除频道成员"
      content={`是否移除频道成员 ${removeMemberInfo.member_display_name} ?`}
      okName="移除"
      onCancel={() => (removeMemberInfo = null)}
      onOk={() => removeMember()}
    />
  {/if}
</div>
